import 'package:flutter/material.dart';
import '/components/page/common.dart';
import '../../widgets/publish_button.dart';
import '/utils/dialog.dart';

// 编辑朋友圈文案页面
class EditArticlePage extends StatefulWidget {
  const EditArticlePage({super.key});

  @override
  State<EditArticlePage> createState() => _EditArticlePageState();
}

class _EditArticlePageState extends State<EditArticlePage> {

  final ValueNotifier<String> _textNotifier = ValueNotifier('');

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, Object? result) async {
        if (didPop) {
          return;
        }
        final bool shouldPop = await customShowDialog(
            context,
            tipText: '直接退出，不保留此次编辑？'
        ) ?? false;
        if (context.mounted && shouldPop) {
          Navigator.pop(context);
        }
      },
      child: CommonPage(
        isShowLine: true,
        actions: [
          PublishButton(
            textNotifier: _textNotifier,
          )
        ],
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: EditArticleWidget(
            onTextChanged: (text) {
              _textNotifier.value = text;
            },
          ),
        ),
      ),
    );
  }
}

// 编辑文案的主体组件
class EditArticleWidget extends StatefulWidget {
  final ValueChanged<String> onTextChanged;

  const EditArticleWidget({super.key, required this.onTextChanged});

  @override
  State<EditArticleWidget> createState() => _EditArticleWidgetState();
}

class _EditArticleWidgetState extends State<EditArticleWidget> {
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      widget.onTextChanged(_controller.text);
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: TextField(
        controller: _controller,
        decoration: const InputDecoration(
          labelText: '输入文章内容',
          border: OutlineInputBorder(),
        ),
        maxLines: 5,
      ),
    );
  }
}
